import os
import json
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量，请用百炼API Key将下行替换为：api_key="sk-xxx",
    api_key="sk-e7884af2481a422ea6cd474faeef3324",
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-max-latest",  # 此处以qwen-plus为例，可按需更换模型名称。模型列表：https://help.aliyun.com/zh/model-studio/getting-started/models
    messages=[
        {'role': 'system', 'content': 'You are a helpful assistant.'},
        {'role': 'user', 'content': '每天早上吃什么最健康？'}],
)


print(completion.model_dump_json())

json_string = completion.model_dump_json()


# 将 JSON 字符串转换为 Python 字典
data = json.loads(json_string)

# 提取各个字段
# id_value = data['id']  # 提取 id
# choices_value = data['choices']  # 提取 choices
# created_value = data['created']  # 提取 created

# 从 choices 中提取 content, refusal, 和 role
content_value = data['choices'][0]['message']['content']  # 提取 content
# refusal_value = data['choices'][0]['message']['refusal']  # 提取 refusal
# role_value = data['choices'][0]['message']['role']  # 提取 role

# 打印提取的字段
# print("id:", id_value)
# print("choices:", choices_value)
# print("created:", created_value)
print("content:", content_value)
# print("refusal:", refusal_value)
# print("role:", role_value)